package com.example.prison.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@ControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     *系统异常处理，比如：404,500
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Response defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        logger.error("", e);
        Response r = new Response();
        r.setMessage(e.getMessage());
        //System.out.println(e.getMessage());
        if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
            r.setStatus("404");
        } else if (Objects.equals(e.getMessage(), "no login! 用户未登录，请重新登录！")){
            r.setStatus("401");
        } else if (Objects.equals(e.getMessage(), "token已过期，请重新登录！")){
            r.setStatus("402");
        } else {
            r.setStatus("500");
        }
        r.setData(null);
//        r.setStatus(false);
        return r;
    }

}
